package com.bto.solar.work.lease;

import com.bto.solar.work.constant.*;
import com.bto.solar.work.dto.ApprovalReq;
import com.bto.solar.work.dto.lease.LeaseApprovalNotifyReq;
import com.bto.solar.work.entity.LeaseReview;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.entity.OrderState;
import com.bto.solar.work.service.BtoOperateLogService;
import com.bto.solar.work.service.BtoOrderStateService;
import com.bto.solar.work.service.biz_stage_handler.LeaseSignedHandler;
import com.bto.solar.work.service.biz_stage_handler.LeaseSyncProjectHandler;
import com.bto.solar.work.service.biz_stage_handler.StageHandlerFactory;
import com.bto.solar.work.utils.NullUtils;
import com.bto.solar.work.utils.StringUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LeaseStateHandler {
    @Autowired
    private StageHandlerFactory stageHandlerFactory;
    @Autowired
    private BtoOrderStateService btoOrderStateService;
    @Autowired
    private BtoOperateLogService optLog;

    public void decideLeaseStateToBtoState(OrderBase orderBase, LeaseReview leaseReviewByDb, LeaseApprovalNotifyReq.PrjProjectOperatingLeaseStatus leaseStatus) {
        decideLeaseState(leaseReviewByDb, leaseStatus);
        //预审状态
        if (StringUtils.isNotEmpty(leaseStatus.getTenantStatus())) {
            val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.PRE_APPROVAL.getStageId());
            if (LeaseStateEnum.REJECT.getStateId().equals(leaseStatus.getTenantStatus())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.PRE_APPROVAL.getStageId(),
                        BizTaskEnum.TASK_YSXX.getTaskId(), Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //承租人预审状态--拒绝(订单终止)
                handler.updateToApprovalRejectState(orderBase.getOrderId(), BizStageEnum.PRE_APPROVAL.getStageId(),
                        BizTaskEnum.TASK_YSXX.getTaskId(), Constants.APPROVAL_LEASE, leaseStatus.getReason());


            } else if (LeaseStateEnum.APPROVED.getStateId().equals(leaseStatus.getTenantStatus())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.PRE_APPROVAL.getStageId(),
                        BizTaskEnum.TASK_YSXX.getTaskId(), Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //承租人预审状态--通过(订单状态变更，下一个阶段：踏勘阶段)
                handler.updateToApprovalPassState(orderBase.getOrderId(), BizStageEnum.PRE_APPROVAL.getStageId(),
                        BizTaskEnum.TASK_YSXX.getTaskId(), Constants.APPROVAL_LEASE);


            } else if (LeaseStateEnum.NEW.getStateId().equals(leaseStatus.getTenantStatus())
                    || LeaseStateEnum.APPROVING.getStateId().equals(leaseStatus.getTenantStatus())) {
                //承租人预审状态--待审核（无需走业务流程）
            }
        }



        //风险审核状态
        if (StringUtils.isNotEmpty(leaseStatus.getProjectStatus())) {
            val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.LEASE_SYNC_PROJECT.getStageId());
            if (LeaseStateEnum.APPROVED.getStateId().equals(leaseStatus.getProjectStatus())) {

                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.LEASE_SYNC_PROJECT.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //风险审核状态--通过
                handler.updateToApprovalPassState(orderBase.getOrderId(), BizStageEnum.LEASE_SYNC_PROJECT.getStageId(),
                        null, Constants.APPROVAL_LEASE);

            }//越秀是 REJECTED  退回
            else if (leaseStatus.getProjectStatus().contains(LeaseStateEnum.REJECT.getStateId()) ||
            LeaseStateEnum.APPROVED_RETURN.getStateId().equals(leaseStatus.getProjectStatus())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.LEASE_SYNC_PROJECT.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //风险审核状态--拒绝(退回博通勘察审核员出)
                handler.updateToApprovalRejectState(orderBase.getOrderId(), BizStageEnum.LEASE_SYNC_PROJECT.getStageId(),
                        null, Constants.APPROVAL_LEASE, leaseStatus.getReason());


            } else if (LeaseStateEnum.CLOSED.getStateId().equals(leaseStatus.getProjectStatus())) {

                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.LEASE_SYNC_PROJECT.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_CLOSE_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //风险审核状态--取消-撤单
                ((LeaseSyncProjectHandler)handler).updateToCloseState(orderBase.getOrderId(), BizStageEnum.LEASE_SYNC_PROJECT.getStageId(),
                        null, Constants.APPROVAL_LEASE, leaseStatus.getReason());

            } else if (LeaseStateEnum.NEW.getStateId().equals(leaseStatus.getProjectStatus())
                    || LeaseStateEnum.APPROVING.getStateId().equals(leaseStatus.getProjectStatus())) {
                //风险审核状态--待审核（无需走业务流程）
            }
        }

        //合同文本状态（农户）
        if (StringUtils.isNotEmpty(leaseStatus.getContractTextStatus())) {
            val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.LEASE_SIGN.getStageId());
            if (LeaseStateEnum.UNCREATED.getStateId().equals(leaseStatus.getContractTextStatus())) {
                //未生成
            }
            else if (LeaseStateEnum.CREATED.getStateId().equals(leaseStatus.getContractTextStatus())) {
                //已生成（下一阶段：合同签约）
                OrderState signedOrderState = btoOrderStateService.getOrderState(orderBase.getOrderId(), BizStageEnum.LEASE_SIGN.getStageId(),
                        BizTaskEnum.TASK_HTQY.getTaskId(), BizTaskStateEnum.SIGNED.getStateId());
                //重新签约
                if(NullUtils.isNotNull(signedOrderState)){
                    ((LeaseSignedHandler)handler).leaseReSigned(orderBase.getOrderId());
                }
            }
            else if (LeaseStateEnum.UNAUDITED.getStateId().equals(leaseStatus.getContractTextStatus())) {
                //待审核--承租人签署完毕 --  重新签约
                OrderState orderTaskState = btoOrderStateService.getOrderTaskState(orderBase.getOrderId(), BizStageEnum.LEASE_SIGN.getStageId(),
                        BizTaskEnum.TASK_HTQY.getTaskId());
                if(NullUtils.isNotNull(orderTaskState)) {
                    if(BizTaskStateEnum.SIGNED.getStateId().equals(orderTaskState.getStateId())){
                        ((LeaseSignedHandler)handler).leaseReSigned(orderBase.getOrderId());
                    }
                }

            }
            else if (LeaseStateEnum.AUDITED.getStateId().equals(leaseStatus.getContractTextStatus())) {
                //已审核--农户投放审查通过
            }
            else if (LeaseStateEnum.SIGNED.getStateId().equals(leaseStatus.getContractTextStatus())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.LEASE_SIGN.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.SIGNED.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //已签约--盖章完成
                handler.signedState(orderBase.getOrderId() , BizStageEnum.LEASE_SIGN.getStageId() , null);

            }
        }

        //农户投放审查状态
        if (StringUtils.isNotEmpty(leaseStatus.getFarmerSignStatus())) {
            //val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.GRID_CONNECTION.getStageId());
            if (LeaseStateEnum.APPROVED.getStateId().equals(leaseStatus.getFarmerSignStatus())) {

                val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.GRID_CONNECTION.getStageId());

                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.GRID_CONNECTION.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //并网信息--越秀通过
                handler.updateToApprovalPassState(orderBase.getOrderId() , BizStageEnum.GRID_CONNECTION.getStageId() , null , Constants.APPROVAL_LEASE);

            } else if (leaseStatus.getFarmerSignStatus().contains(LeaseStateEnum.REJECT.getStateId())) {
                //查询施工信息越秀通过--是否存在
                OrderState orderState = btoOrderStateService.getOrderState(orderBase.getOrderId(), BizStageEnum.CONSTRUCT.getStageId(),
                        BizTaskEnum.CONSTRUCT.getTaskId(), BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId());
                //如果不存在施工信息越秀通过--这个是施工信息拒绝
                if (orderState == null) {
                    val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.CONSTRUCT.getStageId());

                    //记录optLog
                    ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.CONSTRUCT.getStageId(),
                            null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId(), leaseStatus.getReason());
                    optLog.setApprovalInfo(approvalReq);

                    //审核拒绝 （10--施工拒绝，备案证信息拒绝）
                    handler.updateToApprovalRejectState(orderBase.getOrderId() , BizStageEnum.CONSTRUCT.getStageId() , null ,
                            Constants.APPROVAL_LEASE ,  leaseStatus.getReason());
                } else {
                    val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.GRID_CONNECTION.getStageId());

                    //记录optLog
                    ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.GRID_CONNECTION.getStageId(),
                            null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId(), leaseStatus.getReason());
                    optLog.setApprovalInfo(approvalReq);

                    //审核拒绝 （10-并网信息拒绝）
                    handler.updateToApprovalRejectState(orderBase.getOrderId() , BizStageEnum.GRID_CONNECTION.getStageId() , null ,
                            Constants.APPROVAL_LEASE ,  leaseStatus.getReason());
                }

            } else if (LeaseStateEnum.WAITING.getStateId().equals(leaseStatus.getFarmerSignStatus())) {
                //等待推送/补充并网以及投放信息 6-04-01
                val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.CONSTRUCT.getStageId());

                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.CONSTRUCT.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //施工信息通过
                handler.updateToApprovalPassState(orderBase.getOrderId() , BizStageEnum.CONSTRUCT.getStageId() , BizStageEnum.CONSTRUCT.getStageId() , Constants.APPROVAL_LEASE);

            } else if (LeaseStateEnum.NEW.getStateId().equals(leaseStatus.getFarmerSignStatus())
                    || LeaseStateEnum.APPROVING.getStateId().equals(leaseStatus.getFarmerSignStatus())) {
                //农户投放审查状态--待审核（感觉无需走业务流程）
            }
        }

        //租后购售电合同补充状态
        if (StringUtils.isNotEmpty(leaseStatus.getContractPowerStatus())) {
            val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.GS_CONTRACT.getStageId());
            if (LeaseStateEnum.UNSUPPLIED.getStateId().equals(leaseStatus.getContractPowerStatus())) {
                //未补充
            } else if (LeaseStateEnum.APPROVED.getStateId().equals(leaseStatus.getContractPowerStatus())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.GS_CONTRACT.getStageId(),
                        BizTaskEnum.TASK_GSDHTXX.getTaskId(), Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //审批通过 (下一个阶段：完成阶段)
                handler.updateToApprovalPassState(orderBase.getOrderId(), BizStageEnum.GS_CONTRACT.getStageId(),
                        BizTaskEnum.TASK_GSDHTXX.getTaskId(), Constants.APPROVAL_LEASE);

            } else if (leaseStatus.getContractPowerStatus().contains(LeaseStateEnum.REJECT.getStateId())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.GS_CONTRACT.getStageId(),
                        BizTaskEnum.TASK_GSDHTXX.getTaskId(), Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_REJECT_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //审批拒绝（退回并网上传员，修改）
                handler.updateToApprovalRejectState(orderBase.getOrderId(), BizStageEnum.GS_CONTRACT.getStageId(),
                        BizTaskEnum.TASK_GSDHTXX.getTaskId(), Constants.APPROVAL_LEASE , leaseStatus.getReason());



            } else if (LeaseStateEnum.REVOKED.getStateId().equals(leaseStatus.getContractPowerStatus())) {

                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.GS_CONTRACT.getStageId(),
                        BizTaskEnum.TASK_GSDHTXX.getTaskId(), Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_CLOSE_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);


                //已撤销
                handler.updateToApprovalRejectState(orderBase.getOrderId(), BizStageEnum.GS_CONTRACT.getStageId(),
                        BizTaskEnum.TASK_GSDHTXX.getTaskId(), Constants.APPROVAL_LEASE , leaseStatus.getReason());


            } else if (LeaseStateEnum.NEW.getStateId().equals(leaseStatus.getContractPowerStatus())
                    || LeaseStateEnum.APPROVING.getStateId().equals(leaseStatus.getContractPowerStatus())) {
                //待审批（无需走业务流程）
            }
        }

        //投放款付款申请状态
//        if (StringUtils.isNotEmpty(leaseStatus.getPaymentApplyStatus())) {
//            if (LeaseStateEnum.APPROVED.getStateId().equals(leaseStatus.getPaymentApplyStatus())) {
//                //TODO 审核通过
//            } else if (LeaseStateEnum.REJECTED.getStateId().equals(leaseStatus.getPaymentApplyStatus())) {
//                //TODO 审核拒绝
//            } else if (LeaseStateEnum.CANCEL.getStateId().equals(leaseStatus.getPaymentApplyStatus())) {
//                //TODO 取消
//            } else if (LeaseStateEnum.BACK.getStateId().equals(leaseStatus.getPaymentApplyStatus())) {
//                //TODO 撤回
//            } else if (LeaseStateEnum.NEW.getStateId().equals(leaseStatus.getPaymentApplyStatus())
//                    || LeaseStateEnum.APPROVING.getStateId().equals(leaseStatus.getPaymentApplyStatus())) {
//                //TODO 待审核
//            }
//        }

        //投放款支付状态
//        if (StringUtils.isNotEmpty(leaseStatus.getPaymentStatus())) {
//            if (LeaseStateEnum.FAILURE.getStateId().equals(leaseStatus.getPaymentStatus())) {
//                //TODO 支付失败
//            } else if (LeaseStateEnum.PAID.getStateId().equals(leaseStatus.getPaymentStatus())) {
//                //TODO 已支付
//            } else if (LeaseStateEnum.NEW.getStateId().equals(leaseStatus.getPaymentStatus())
//                    || LeaseStateEnum.PAYING.getStateId().equals(leaseStatus.getPaymentStatus())) {
//                //TODO 待支付
//            }
//        }

        //合同状态
        if (StringUtils.isNotEmpty(leaseStatus.getContractStatus())) {
            val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.LEASE_SIGN.getStageId());
            if (LeaseStateEnum.SIGN.getStateId().equals(leaseStatus.getContractStatus())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.LEASE_SIGN.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.APPROVAL_PASS_LEASE.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //投放审查通过
                handler.signedState(orderBase.getOrderId() , BizStageEnum.LEASE_SIGN.getStageId() , null);

            }
            else if (LeaseStateEnum.INCEPT.getStateId().equals(leaseStatus.getContractStatus())) {
                //记录optLog
                ApprovalReq approvalReq = getApprovalReq(orderBase.getOrderId(), BizStageEnum.LEASE_SIGN.getStageId(),
                        null, Constants.APPROVAL_LEASE, BizTaskStateEnum.INCEPT.getStateId(), leaseStatus.getReason());
                optLog.setApprovalInfo(approvalReq);

                //起租
                ((LeaseSignedHandler)handler).inceptState(orderBase.getOrderId() , BizStageEnum.LEASE_SIGN.getStageId() , null);

            }
            else if (LeaseStateEnum.PENDING.getStateId().equals(leaseStatus.getContractStatus())) {
                //暂挂（进行变更）
            } else if (LeaseStateEnum.TERMINATE.getStateId().equals(leaseStatus.getContractStatus())) {
                //合同结束
            } else if (LeaseStateEnum.CANCEL.getStateId().equals(leaseStatus.getContractStatus())) {
                //取消
            }
        }
    }

    public ApprovalReq getApprovalReq(String orderId, String stageId, String taskId, String approvalType, String result, String reason) {
        ApprovalReq approvalReq = new ApprovalReq();
        approvalReq.setOrderId(orderId);//订单ID
        approvalReq.setStageId(stageId);//阶段ID
        approvalReq.setTaskId(taskId);//任务ID
        approvalReq.setApprovalType(approvalType);//审核类型
        approvalReq.setResult(result);//审核结果
        approvalReq.setRejectReason(reason);//审核内容
        approvalReq.setApprover(0L);//审核人--越秀
        return approvalReq;
    }

    public void decideLeaseState(LeaseReview leaseReviewByDb, LeaseApprovalNotifyReq.PrjProjectOperatingLeaseStatus prjProjectOperatingLeaseStatus) {
        if (null == leaseReviewByDb) {
            return;
        }

        //tenantStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getTenantStatus())) {
            if (leaseReviewByDb.getTenantStatus().equals(prjProjectOperatingLeaseStatus.getTenantStatus())) {
                prjProjectOperatingLeaseStatus.setTenantStatus(null);
            }
        }
        //projectStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getProjectStatus())) {
            if (leaseReviewByDb.getProjectStatus().equals(prjProjectOperatingLeaseStatus.getProjectStatus())) {
                prjProjectOperatingLeaseStatus.setProjectStatus(null);
            }
        }
        //farmerSignStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getFarmerSignStatus())) {
            if (leaseReviewByDb.getFarmerSignStatus().equals(prjProjectOperatingLeaseStatus.getFarmerSignStatus())) {
                prjProjectOperatingLeaseStatus.setFarmerSignStatus(null);
            }
        }
        //paymentApplyStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getPaymentApplyStatus())) {
            if (leaseReviewByDb.getPaymentApplyStatus().equals(prjProjectOperatingLeaseStatus.getPaymentApplyStatus())) {
                prjProjectOperatingLeaseStatus.setPaymentApplyStatus(null);
            }
        }
        //paymentStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getPaymentStatus())) {
            if (leaseReviewByDb.getPaymentStatus().equals(prjProjectOperatingLeaseStatus.getPaymentStatus())) {
                prjProjectOperatingLeaseStatus.setPaymentStatus(null);
            }
        }
        //contractStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getContractStatus())) {
            if (leaseReviewByDb.getContractStatus().equals(prjProjectOperatingLeaseStatus.getContractStatus())) {
                prjProjectOperatingLeaseStatus.setContractStatus(null);
            }
        }
        //contractTextStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getContractTextStatus())) {
            if (leaseReviewByDb.getContractTextStatus().equals(prjProjectOperatingLeaseStatus.getContractTextStatus())) {
                prjProjectOperatingLeaseStatus.setContractTextStatus(null);
            }
        }
        //contractPowerStatus
        if (StringUtils.isNotBlank(leaseReviewByDb.getContractPowerStatus())) {
            if (leaseReviewByDb.getContractPowerStatus().equals(prjProjectOperatingLeaseStatus.getContractPowerStatus())) {
                prjProjectOperatingLeaseStatus.setContractPowerStatus(null);
            }
        }
    }

}
